package com.tomatozq163.sharding.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

@Slf4j
public class AESUtil {
    /**
     * mysql默认取秘钥的ascii编码前16位
     */
    public static String MYSQL_ENC_KEY = "123456abc";

    /**
     * AES加密字符串
     * @param content 需要被加密的字符串
     * @param strKey 秘钥
     * @return 密文
     */
    public static String encrypt(String content, String strKey) {
        String encStr = null;

        try {
            byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);

            SecretKey key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] data = content.getBytes("UTF-8");
            byte[] encBytes = cipher.doFinal(data);

            encStr = Base64.encode(encBytes);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
        }

        return encStr;
    }

    /**
     * 解密AES加密过的字符串
     * @param encStr AES加密过过的内容
     * @param strKey 秘钥
     * @return 明文
     */
    public static String decrypt(String encStr, String strKey) {
        String plainText = "";

        try {
            byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);

            SecretKey key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器

            byte[] data = Base64.decode(encStr);
            byte[] result = cipher.doFinal(data);

            plainText = new String(result,"UTF-8");
        } catch (Exception ex) {
            log.error(encStr + "," + ex.getMessage());
        }

        return plainText;
    }

    public static void main(String[] args) {
        String encStr = AESUtil.encrypt("421002198311131816",AESUtil.MYSQL_ENC_KEY);
        System.out.println(encStr);

        String plainText = AESUtil.decrypt(encStr,AESUtil.MYSQL_ENC_KEY);
        System.out.println(plainText);
    }
}
